package service

import (
	"errors"

	"mutu/misc/conf"
	"mutu/misc/log"
	"mutu/models"
)

type BossManager struct {
}

var (
	BossService = BossManager{}
)

func (p BossManager) DeductScore(score int, userId string, comment string) (int, error) {
	amount := &models.ScoreAmount{
		UserId: userId,
	}
	if err := models.Orm.Read(amount, "UserId"); err != nil {
		log.Log.Error("扣除积分-读取用户<%s>积分出错, %s", userId, err)
		return 0, err
	}
	if amount.Score < score {
		return amount.Score, errors.New("积分不足")
	}
	originScore := amount.Score
	amount.Score = originScore - score
	if _, err := models.Orm.Update(amount, "Score", "updateAt"); err != nil {
		log.Log.Error("扣除积分-更新用户<%s>积分出错, %s", userId, err)
		return originScore, err
	}

	tail := &models.ScoreTail{
		UserId:  userId,
		Flag:    conf.F_Boss_Expend,
		Score:   score,
		Comment: comment,
	}
	if _, err := models.Orm.Insert(tail); err != nil {
		log.Log.Error("扣除积分-保存用户<%s>积分明细出错, %s", userId, err)
		return amount.Score, err
	}
	return amount.Score, nil

}
